<template>
  <el-dialog v-model="visible" title="导入文档" width="50%">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="文件上传" name="file">
        <el-upload
          class="upload-demo"
          drag
          multiple
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          :file-list="fileList"
          :accept="acceptTypes"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              支持 PDF/DOC/DOCX/PPT/PPTX/WPS/PPSX (≤200MB),
              XLS/XLSX/MD/TXT/CSV/HTML (≤20MB), JPG/PNG/JPEG/TIFF/BMP/GIF
              (≤50MB)
            </div>
          </template>
        </el-upload>

        <div class="upload-actions" v-if="fileList.length > 0">
          <el-button
            type="primary"
            @click="submitUpload"
            :loading="uploading"
            :disabled="uploading"
          >
            开始上传
          </el-button>
          <el-button @click="clearFiles">清空</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible"
    title="文件上传结果"
    width="600px"
    :close-on-click-modal="false"
  >
    <!-- 成功列表 -->
    <div v-if="successFiles.length > 0" style="width: 100%;">
      <el-table width="100%" :data="successFiles" border>
        <el-table-column prop="originalname" label="文件名" >
          <template #default="{ row }">
            <el-icon color="#67C23A"><Document /></el-icon>
            <span class="ml-1">{{ row.originalname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default>
            <el-tag type="success" effect="plain">成功</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 失败列表 -->
    <div v-if="failedFiles.length > 0" class="mt-4" style="width: 100%;">
      <el-table :data="failedFiles" border width="100%">
        <el-table-column prop="originalname" label="文件名">
          <template #default="{ row }">
            <el-icon color="#F56C6C"><Document /></el-icon>
            <span class="ml-1">{{ row.originalname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态"  align="center">
          <template #default>
            <el-tag type="danger" effect="plain">失败</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRoute } from "vue-router";
import { UploadFilled } from "@element-plus/icons-vue";
import { uploadFiles } from "@/api/modules/auth";
import { ElMessage } from "element-plus";
const route = useRoute();
const props = defineProps({
  modelValue: Boolean,
});
// 获取应用ID
const appId = computed(() => route.params.id);

const emit = defineEmits(["update:modelValue", "success"]);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const activeTab = ref("file");
const fileList = ref([]);
const webForm = ref({
  url: "",
});
const uploading = ref(false);
const uploadProgress = ref(0);
const uploadStatus = ref("");
const currentUploadFile = ref("");
const uploadedCount = ref(0);

const acceptTypes =
  ".pdf,.doc,.docx,.ppt,.pptx,.wps,.ppsx,.xlsx,.xls,.md,.txt,.csv,.html,.jpg,.png,.jpeg,.tiff,.bmp,.gif";

// 文件选择变化时的处理
const handleFileChange = (file, files) => {
  const fileType = file.name.split(".").pop().toLowerCase();
  const isLargeDoc = [
    "pdf",
    "doc",
    "docx",
    "ppt",
    "pptx",
    "wps",
    "ppsx",
  ].includes(fileType);
  const isMediumDoc = ["xlsx", "xls", "md", "txt", "csv", "html"].includes(
    fileType
  );
  const isImage = ["jpg", "png", "jpeg", "tiff", "bmp", "gif"].includes(
    fileType
  );

  // 验证文件大小
  if (isLargeDoc && file.size > 200 * 1024 * 1024) {
    ElMessage.error(`${file.name} 超过200MB限制`);
    return false;
  }

  if (isMediumDoc && file.size > 20 * 1024 * 1024) {
    ElMessage.error(`${file.name} 超过20MB限制`);
    return false;
  }

  if (isImage && file.size > 50 * 1024 * 1024) {
    ElMessage.error(`${file.name} 超过50MB限制`);
    return false;
  }

  // 更新文件列表
  fileList.value = files;
  return true;
};
const successFiles = ref([]);
const failedFiles = ref([]);
const dialogVisible = ref(false)
// 提交上传
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请先选择要上传的文件");
    return;
  }
  successFiles.value = [];
  failedFiles.value = [];
  uploading.value = true;
  uploadStatus.value = "";
  uploadedCount.value = 0;

  try {
    const formData = new FormData();
    fileList.value.forEach((file) => {
      formData.append("files", file.raw);
      formData.append("appId", appId.value);
    });
    const res = await uploadFiles(formData);
    const results = res.results;
    successFiles.value = results.filter(item => item.success)
    failedFiles.value = results.filter(item => !item.success)
    dialogVisible.value = true
    emit("success");
    clearFiles();
    visible.value = false;
  } catch (error) {
    uploadStatus.value = "exception";
    ElMessage.error(`文件上传失败: ${error.message}`);
  } finally {
    uploading.value = false;
  }
};

// 清空文件列表
const clearFiles = () => {
  fileList.value = [];
  uploadProgress.value = 0;
  currentUploadFile.value = "";
  uploadedCount.value = 0;
};

// 网页导入
const importWeb = async () => {
  if (!webForm.value.url) {
    ElMessage.error("请输入网页URL");
    return;
  }

  try {
    ElMessage.success("网页导入成功");
    emit("success");
    visible.value = false;
  } catch (e) {
    ElMessage.error("网页导入失败");
  }
};
</script>

<style scoped>
.upload-demo {
  margin-bottom: 20px;
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

.upload-progress {
  margin-top: 20px;
}

.upload-info {
  margin-top: 10px;
  text-align: center;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}
</style>